<template>
  <div>
    <div class="inspec_title">
      <div>检查报告</div>
      <el-button @click="$emit('send')">返回</el-button>
    </div>
    <div class="inspec">
      <el-upload
        ref="upload"
        action=""
        :auto-upload="false"
        :on-change="selImg"
        :show-file-list="false"
      >
        <el-button slot="trigger" type="primary">报告单识别</el-button>
      </el-upload>

      <el-table :data="tableData" style="margin: 10px 0 15px">
        <el-table-column label="项目" prop="item_name" />
        <el-table-column label="代码" prop="item_code" />
        <el-table-column label="检查结果">
          <template slot-scope="scope">
            <el-input
              v-if="
                scope.row.item_type == 'input_num' ||
                scope.row.item_type == 'input_str'
              "
              v-model="scope.row.item_value"
              placeholder="请输入检查结果"
            />
            <div v-if="scope.row.item_type == 'input_flie'">
              <el-upload
                action="https://devapi.jbkl.com/api/upload_img"
                class="upload-demo"
                :limit="3"
                list-type="picture"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="
                  (res) => {
                    return uploadSuccess(res, scope.row)
                  }
                "
                :show-file-list="false"
              >
                <img
                  v-if="scope.row.item_value"
                  class="avatar"
                  :src="scope.row.item_value"
                  width="100px"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="参考值" prop="item_scope">
          <template slot-scope="scope">
            <div v-for="(items, index) in scope.row.item_scope" :key="index">
              {{ items.label }}
              {{ items.value }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单位" prop="unit" />
      </el-table>

      <div style="text-align: center">
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </div>
    <!-- 图片裁剪对话框 -->
    <el-dialog title="图片裁剪" :visible.sync="imgDialog" width="70%">
      <div style="display: flex">
        <div style="width: 50%">
          <el-tag>按照图片示例，截取红色框部分（检查项目和结果）</el-tag>
          <img class="crop_img" src="@/assets/images/crop.png" />
        </div>
        <div style="width: 20px"></div>
        <Vue-cropper
          ref="cropper"
          auto-crop
          :full="option.full"
          :img="option.img"
          :output-size="option.size"
          :output-type="option.outputType"
          style="width: 50%; height: 450px"
        />
      </div>
      <div slot="footer">
        <el-button type="primary" @click="uploadImg">选择图片</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { VueCropper } from 'vue-cropper'
  import { ocrToJson } from '@/api/public'
  import { getReportDetail, saveReportItem } from '@/api/report'

  export default {
    components: {
      VueCropper,
    },
    props: {
      oSelInfo: {
        type: Object,
        default() {
          return {}
        },
      },
    },
    data() {
      return {
        tableData: [],
        order_id: '',
        imgDialog: false,
        option: {
          img: '', // 裁剪图片地址
          size: 1, // 裁剪生成图片的质量
          outputType: 'png', // 裁剪生成图片的格式
          full: false, // false按原比例裁切图片，不失真
        },
      }
    },
    mounted() {
      const data = {
        attribute_id: this.oSelInfo.attribute_id,
        member_id: this.oSelInfo.member_id,
        res_item_id: this.oSelInfo.res_item_id,
      }
      getReportDetail(data).then((e) => {
        this.order_id = e.data.order_id
        this.tableData = e.data.item
      })
    },
    methods: {
      tabsClick() {
        // console.log(e)
      },
      // 移除选中模板项
      remov(index) {
        this.tableData.splice(index, 1)
      },
      // 选择图片，并转换成base64，在裁剪组件中显示
      selImg(e) {
        const _that = this
        let oFReader = new FileReader()
        oFReader.readAsDataURL(e.raw) // 读取图片文件对象，将其读成 DataURL 形式
        // 读取成功时触发
        oFReader.onload = function (res) {
          _that.option.img = res.target.result // 将读取的结果赋值给裁剪组件配置
          _that.imgDialog = true // 打开图片裁剪对话框
          _that.$refs.upload.clearFiles() // 每次选择图片后，手动清空上传文件列表，防止缓存堆积
        }
        // 读取失败时触发
        oFReader.onerror = function () {
          this.$message.error('图片选择失败，请重新选择图片')
        }
      },
      // 上传裁剪图片
      uploadImg() {
        this.$refs.cropper.getCropBlob((file) => {
          let formData = new FormData()
          formData.append('file', file)
          formData.append('goods_id', this.oSelInfo.goods_id)

          // const data = {
          //   id: 10,
          // }
          // 调用图片上传接口
          ocrToJson(formData).then((res) => {
            this.tableData.forEach((e) => {
              res.forEach((k) => {
                if (k.id == e.item_id) {
                  // console.log(e)
                  e.item_value = k.result
                }
              })
            })

            this.$message.success('图片上传成功')
            this.imgDialog = false
          })
        })
      },
      // 保存
      save() {
        const add = []
        const data = JSON.parse(JSON.stringify(this.tableData))
        data.forEach((e) => {
          e.item_scope.forEach((j) => {
            if (j.type == 'min') {
              //
              e.min = j.value || 10
            }
            if (j.type == 'max') {
              e.max = j.value || 50
            }
          })
          if (e.item_value >= e.min && e.item_value <= e.max) {
            e.compare = 'normal'
          } else {
            if (e.item_value < e.min) {
              e.compare = 'low'
            } else {
              e.compare = 'normal'
            }
            if (e.item_value > e.max) {
              e.compare = 'high'
            } else {
              e.compare = 'normal'
            }
            if (!e.min && !e.max) {
              e.compare = 'normal'
            }
          }
          add.push({
            id: e.id,
            item_value: e.item_value,
            compare: e.compare,
          })
        })

        const pada = {
          infos: JSON.stringify(add),
          order_id: this.order_id,
        }
        saveReportItem(pada).then((e) => {
          console.log(e)
          this.$emit('send')
        })
      },
      handleRemove(file) {
        console.log(file)
      },
      handlePreview(file) {
        console.log(file)
      },
      uploadSuccess(r, k) {
        k.item_value = r.data
        console.log(r)
        console.log(k)
      },
    },
  }
</script>

<style scoped>
  .inspec_title {
    padding: 10px 15px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .inspec {
    padding: 15px;
  }
  .crop_img {
    width: 100%;
    height: 450px;
    margin-top: 15px;
  }
</style>
